﻿
using System.Collections;


namespace Framework.Generics
{

    //单例模型
    public class Singleton<T>
        where T : new()
    {
        /// <summary>
        /// 静态句柄
        /// </summary>
        public static T Instance { get { return GetInstance(); } }

        #region static instance
        /// <summary>
        /// 静态句柄
        /// </summary>
        private static T instance;

        /// <summary>
        /// 获取单例句柄
        /// </summary>
        /// <param name="create"></param>
        /// <returns></returns>
        protected static T GetInstance(bool create)
        {
            // instance 为空时或者强制create一个时创建
            if (instance == null || create)
            {
                //移除旧的实例
                if (instance != null)
                {
                    instance = default(T);
                }
                //创建新实例
                instance = new T();
            }
            return instance;
        }

        /// <summary>
        /// 获取单例句柄, 返回旧句柄.
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        protected T SetInstance(T inst)
        {
            T old = instance;
            instance = inst;
            return old;
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <returns></returns>
        public static T GetInstance()
        {
            return GetInstance(false);
        }

        #endregion
    }
    


}